package com.ubhave.powertracker;

import java.util.Calendar;
import java.util.Date;

import com.ubhave.powertracker.R;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.DialogPreference;
import android.preference.PreferenceManager;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 * Custom preference for time selection. Hour and minute are persistent and
 * stored separately as ints in the underlying shared preferences under keys
 * KEY.hour and KEY.minute, where KEY is the preference's key.
 * 
 * Original class from twodee.org, modified by Charlie Hargood.
 */
public class DailyUpdateTimePreference extends DialogPreference {

	//Alarm Manager for notifications
	static AlarmManager alarmManager;
	
  /** The widget for picking a time */
  private TimePicker timePicker;

  /** Default hour */
  private static final int DEFAULT_HOUR = 8;

  /** Default minute */
  private static final int DEFAULT_MINUTE = 0;

  SharedPreferences settings;
  
  /**
   * Creates a preference for choosing a time based on its XML declaration.
   *
   * @param context
   * @param attributes
   */
  public DailyUpdateTimePreference(Context context,
                        AttributeSet attributes) {
    super(context, attributes);
    setPersistent(false);
    alarmManager = (AlarmManager)getContext().getSystemService(getContext().ALARM_SERVICE);
    settings =PreferenceManager.getDefaultSharedPreferences(PowerTrackerApplication.getContext());
    
  }

  /**
   * Initialize time picker to currently stored time preferences.
   *
   * @param view
   * The dialog preference's host view
   */
  @Override
  public void onBindDialogView(View view) {
    super.onBindDialogView(view);
    timePicker = (TimePicker) view.findViewById(R.id.prefTimePicker);
    timePicker.setIs24HourView(DateFormat.is24HourFormat(timePicker.getContext()));
    timePicker.setCurrentHour(getSharedPreferences().getInt(getKey() + ".hour", DEFAULT_HOUR));
    timePicker.setCurrentMinute(getSharedPreferences().getInt(getKey() + ".minute", DEFAULT_MINUTE));    
  }

  /**
   * Handles closing of dialog. If user intended to save the settings, selected
   * hour and minute are stored in the preferences with keys KEY.hour and
   * KEY.minute, where KEY is the preference's KEY.
   *
   * @param okToSave
   * True if user wanted to save settings, false otherwise
   */
  @Override
  protected void onDialogClosed(boolean okToSave) {
    super.onDialogClosed(okToSave);
    if (okToSave) {
      timePicker.clearFocus();
      SharedPreferences.Editor editor = getEditor();
      editor.putInt(getKey() + ".hour", timePicker.getCurrentHour());
      editor.putInt(getKey() + ".minute", timePicker.getCurrentMinute());
      editor.commit();
                  
      
      Intent myIntent = new Intent(getContext() , DailyUpdateReminderNotification.class);     
      
      PendingIntent pendingIntent = PendingIntent.getService(getContext(), 0, myIntent, 0);

     
      Calendar calendar = Calendar.getInstance();
      calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
      calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());
      calendar.set(Calendar.SECOND, 00);
      
      Calendar current = Calendar.getInstance();
      if(calendar.before(current)){
    	  calendar.setTimeInMillis(calendar.getTimeInMillis()+(24*60*60*1000));
      }
          
      long interval = 24*60*60*1000;
      if(settings.getBoolean("AlarmDebugModeOn", false))
    	  interval=2*60*1000;
      
      alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), interval , pendingIntent);  //set repeating every 24 hours
      //alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 30*1000 , pendingIntent);  //set repeating every 24 hours
      
      
      Log.i("POWeR Tracker Special:", "Set Daily Update Alarm: "+calendar.getTimeInMillis());
    }
  }
}